// import Schema from 'async-validator'
const Schema = require('async-validator/dist-node').default

/**
 * 请求参数校验
 * 参考 https://cloud.tencent.com/developer/article/1988905
 * @param ctx
 * @param rules
 * @returns
 */
const validate = async (ctx, rules) => {
  const validator = new Schema(rules)
  let data = null
  switch (ctx.method) {
    case 'GET':
      data = ctx.query
      break
    case 'POST':
      data = ctx.request.body
      break
    case 'PUT':
      data = ctx.request.body
      break
    case 'DELETE':
      data = ctx.query
      break
    default:
      data = ctx.request.body
  }

  return await validator
    .validate(data)
    .then(() => {
      return {
        data,
        error: false
      }
    })
    .catch((err) => {
      // 异常返回给客户端
      ctx.body = {
        code: 400,
        msg: err.errors.map(r => r.message).join(';')
      }
      return {
        data: {},
        error: true
      }
    })
}

module.exports = validate
